﻿using HYDataCapture.Views;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HY.WinForm;
using HYDataCapture.Enums;

namespace HYDataCapture.Forms
{
    public partial class Win007DataCaptureForm : BaseForm, Views.IWin007DataCaptureView
    {
        private readonly Presenters.Win007DataCapturePresenter _Presenter;
        public Win007DataCaptureForm(ILogView view) : base(view)
        {
            InitializeComponent();
            _Presenter = new Presenters.Win007DataCapturePresenter(this);

            tabControl1.TabPages.RemoveAt(1);
        }

        string IWin007DataCaptureView.Log
        {
            set
            {
                _Log.WriteLog(value);
            }
        }

        Win007MatchSaveOptionEnum IWin007DataCaptureView.MatchSaveOption
        {
            get
            {
                return (Win007MatchSaveOptionEnum)toolStripComboBox1.SelectedIndex;
            }
        }

        string[] IWin007DataCaptureView.MatchSaveItems
        {
            set
            {
                toolStripComboBox1.Items.Clear();
                toolStripComboBox1.Items.AddRange(value);
                if (toolStripComboBox1.Items.Count > 0)
                    toolStripComboBox1.SelectedIndex = 0;
            }
        }

        List<string> IWin007DataCaptureView.FilterMatch
        {
            get
            {
                List<string> output = new List<string>();
                for (int i = 0; i < listBox2.Items.Count; ++i)
                    output.Add(listBox2.Items[i].ToString());
                return output;
            }
        }

        int IWin007DataCaptureView.AnalysisDataCaptureProgressValue
        {
            set
            {
                this.toolStripProgressBar1.Value = value;
                Application.DoEvents();
            }
        }

        int IWin007DataCaptureView.AnalysisDataCaptureProgressMax
        {
            set
            {
                this.toolStripProgressBar1.Maximum = value;
            }
        }

        string IWin007DataCaptureView.WaitTime
        {
            set
            {
                this.toolStripStatusLabel3.Text = $"{value}";
            }
        }

        string IWin007DataCaptureView.MatchId
        {
            set
            {
                _MatchIdColumnName = value;
            }

        }

        private string _MatchIdColumnName;

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            _Presenter.DataMenuUrlCapture();
            treeView1.Nodes.Clear();
            var root = treeView1.Nodes.Add("所有赛事");
            root.Tag = "";
            _Presenter.TreeNodeDataList.ForEach(s =>
            {
                var node = root.Nodes.Add(s.Id, s.Text);
                node.Tag = s.Id;
                if (s.ChildNodeList != null)
                {
                    s.ChildNodeList.ForEach(s2 =>
                    {
                        var childnode = node.Nodes.Add(s2.Id,s2.Text);
                        childnode.Tag = s2.Id;
                        if (s2.ChildNodeList != null)
                        {
                            s2.ChildNodeList.ForEach(s3 => {
                                var sonnode = childnode.Nodes.Add(s3.Id, s3.Text);
                                sonnode.Tag = s3.Id;
                            });
                        }
                    });
                }
            });
            root.Expand();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if(treeView1.Nodes.Count>0)
            {
                var root = treeView1.Nodes[0];
                root.Collapse(false);
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (treeView1.Nodes.Count > 0)
            {
                var root = treeView1.Nodes[0];
                root.ExpandAll();
            }
        }

        private void 采集选中赛事ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selnode = treeView1.SelectedNode;
            if (selnode != null)
            {

                var data = _Presenter.GetTreeNodeData(selnode.Tag.ToString());
                if (data == null) return;
                if(data.IsOnlyTitle)
                {
                    MessageBox.Show("请选择具体联赛进行采集");
                    return;
                }
                var dt = _Presenter.DataCapture(data);
                using (DataGridViewBindData bd = new DataGridViewBindData(dataGridView1, delegate
                {
                    return dt;
                }))
                {
                    this.toolStripStatusLabel1.Text = $"记录数：{dt.Rows.Count}";
                }

            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            switch(_Presenter.DataCaptureWithAnalysis())
            {
                case Enums.CaptureStateEnum.Success:
                    {
                        if(myButtonCheck1.Checked)
                        {
                            timer1.Interval = new Random().Next((int)numericUpDown1.Value, (int)numericUpDown2.Value);
                            timer1.Enabled = true;
                            _Log.WriteLog($"{timer1.Interval}毫秒后启动下次采集...");
                        }
                        else
                        {
                            _Log.WriteLog("采集已停止.");
                        }
                    }
                    break;
                case Enums.CaptureStateEnum.Completed:
                    {
                        _Log.WriteLog("采集已完成.");
                        myButtonCheck1.Checked = false;
                    }
                    break;
                case Enums.CaptureStateEnum.NoMatch:
                    {
                        _Log.WriteLog("未能匹配数据，采集已停止.");
                        myButtonCheck1.Checked = false;

                        StartDelayCaptureTimer();

                    }
                    break;
                case Enums.CaptureStateEnum.Exception:
                    {
                        _Log.WriteLog("发生异常，采集已停止.");
                        myButtonCheck1.Checked = false;

                        StartDelayCaptureTimer();
                    }
                    break;
            }


        }

        private void StartDelayCaptureTimer()
        {
            _Log.WriteLog("延迟2分钟后自动恢复采集...");
            timer2.Interval = 1000;
            timer2.Enabled = true;
            this.toolStripStatusLabel3.Visible = true;
        }

        private void myButtonCheck1_Click(object sender, EventArgs e)
        {
            if(myButtonCheck1.Checked)
            {
                var dr = MessageBox.Show("是否保留已采集的分析数据？（如果已采集过）", "请选择", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                var saveLastData = dr == DialogResult.Yes;
                _Presenter.InitDataCaptureWithAnalysis(saveLastData);
                timer1.Interval = 1;
                timer1.Enabled = true;
                this.toolStripProgressBar1.Value = 0;
                _Log.WriteLog("启动采集...");
            }
            else
            {
                _Log.WriteLog("正在停止采集...");
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var result = Microsoft.VisualBasic.Interaction.InputBox("赛事", "请输入");
            listBox1.Items.Add(result);
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if(listBox1.SelectedIndex==-1)
            {
                MessageBox.Show("请先选中一项");
                return;
            }
            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var option = new Models.GetAnalysisDataSearchOption() { TypeList=new List<string>() };
            foreach(var item in listBox1.Items)
            {
                option.TypeList.Add(item.ToString());
            }
            var data = _Presenter.GetAnalysisData(option);
            using (DataGridViewBindData bd = new DataGridViewBindData(dataGridView2, delegate
            {
                return data;
            }))
            {
                this.toolStripStatusLabel2.Text = $"记录数：{data.Rows.Count}";
            }
        }

        private void ExportExcel(DataGridView dgv)
        {
            using (var dlg = new SaveFileDialog())
            {
                dlg.Filter = "Excel Files(*.xlsx)|*.xlsx";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (System.IO.File.Exists(dlg.FileName))
                        {
                            System.IO.File.Delete(dlg.FileName);
                        }
                        using (HY.Utility.ImportExport.ExcelHelper helper = new HY.Utility.ImportExport.ExcelHelper(dlg.FileName))
                        {
                            var dt = dgv.ToDataTable();
                            helper.DataTableToExcel(dt, "导出数据", true);
                        }
                        MessageBox.Show($"文件已导出：{dlg.FileName}");
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show($"发生异常：{ex.Message}");
                    }
                }
            }
        }

        private void 导出为ExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dgv = contextMenuStrip2.SourceControl as DataGridView;
            if (dgv != null)
                ExportExcel(dgv);
        }

        private void Win007DataCaptureForm_Load(object sender, EventArgs e)
        {
            _Presenter.Init();
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                treeView1.ContextMenuStrip = null;
                return;
            }
            treeView1.ContextMenuStrip = contextMenuStrip1;
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var result = Microsoft.VisualBasic.Interaction.InputBox("赛事：", "请输入赛事");
            if (result.Length > 0)
                listBox2.Items.Add(result);
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (listBox2.SelectedIndex != -1)
                listBox2.Items.RemoveAt(listBox2.SelectedIndex);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var dt = _Presenter.FilterCaptureMatch();
            if (dt == null) return;
            var firstindex = dataGridView1.FirstDisplayedScrollingRowIndex;
            using (DataGridViewBindData bd = new DataGridViewBindData(dataGridView1, delegate
            {
                return dt;
            })) { }
            if (dataGridView1.Rows.Count > firstindex)
            {
                dataGridView1.FirstDisplayedScrollingRowIndex = firstindex;
            }
            this.toolStripStatusLabel1.Text = $"记录数：{dt.Rows.Count}";
        }

        private void 访问对应网页ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count>0)
            {
                var row = dataGridView1.SelectedRows[0];
                if (row.IsNewRow) return;
                var id = row.Cells["赛事编号"].Value.ToString();
                System.Diagnostics.Process.Start($"http://zq.win007.com/analysis/{id}.htm");
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            timer2.Enabled = false;
            if (_Presenter.IsCanExecNextCapture())
            {
                this.toolStripStatusLabel3.Visible = false;
                myButtonCheck1.Checked = true;
                timer1.Enabled = true;
            }
            else
                timer2.Enabled = true;
        }

        private void 采集选中项赛事分析ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                var row = dataGridView1.SelectedRows[0];
                if (row.IsNewRow) return;
                if (dataGridView1.Columns.Contains(_MatchIdColumnName))
                {
                    var matchId = row.Cells[_MatchIdColumnName].Value.ToString();
                    _Presenter.InitDataCaptureWithAnalysis(true);
                    _Presenter.DataCaptureWithAnalysis(matchId);
                }
            }
        }

        private void 显示近10场赛事分析数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                var row = dataGridView1.SelectedRows[0];
                if (row.IsNewRow) return;
                if (dataGridView1.Columns.Contains(_MatchIdColumnName))
                {
                    var matchId = row.Cells[_MatchIdColumnName].Value.ToString();
                    var dt = _Presenter.FilterCaptureMatch(matchId);
                    using (var dlg = new Dialogs.Win007MatchAnalysisDataDialog(dt))
                    {
                        dlg.ShowDialog();
                    }
                }
            }
        }

        private void 获取多次循环赛事ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selnode = treeView1.SelectedNode;
            if (selnode != null)
            {
                _Presenter.CaptureMulMatchUrl(selnode.Tag.ToString());
            }
        }
    }
}
